package com.csweimei.rentmanagementtreasure.tenant.viewModel;

import android.app.Application;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.csweimei.rentmanagementtreasure.R;
import com.csweimei.rentmanagementtreasure.base.AppConfig;
import com.csweimei.rentmanagementtreasure.http.entity.BaseResult;
import com.csweimei.rentmanagementtreasure.http.entity.QuarterEntity;
import com.csweimei.rentmanagementtreasure.http.postBean.PostHouseHzBean;
import com.csweimei.rentmanagementtreasure.pop.PopBean;
import com.csweimei.rentmanagementtreasure.pop.PopQuarters;
import com.csweimei.rentmanagementtreasure.pop.PopSelClick;
import com.csweimei.rentmanagementtreasure.pop.PopUtils;
import com.csweimei.rentmanagementtreasure.tenant.ui.act.house.AddMoreHzActivity;
import com.csweimei.rentmanagementtreasure.tenant.ui.act.house.ImproveHouseActivity;
import com.csweimei.rentmanagementtreasure.utils.DialogUtils;
import com.csweimei.rentmanagementtreasure.utils.GlideEngine;
import com.csweimei.rentmanagementtreasure.utils.GlideHandler;
import com.csweimei.rentmanagementtreasure.utils.ValidateUtils;
import com.csweimei.rentmanagementtreasure.utils.permission.MyCustomPopupWindow;
import com.csweimei.rentmanagementtreasure.utils.permission.RxPermissionsUtils;
import com.csweimei.rentmanagementtreasure.utils.uploadUtils.QiNiuYunBean;
import com.csweimei.rentmanagementtreasure.utils.uploadUtils.QiNiuYunUpload;
import com.csweimei.rentmanagementtreasure.utils.uploadUtils.QiNiuYunUploadCallBack;
import com.csweimei.rentmanagementtreasure.viewModel.TitleVM;
import com.csweimei.rentmanagementtreasure.weight.selAddress.MyAddressPickerView;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gtdev5.geetolsdk.mylibrary.util.GsonUtils;
import com.gtdev5.geetolsdk.mylibrary.util.LogUtils;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class AddHouseHzVm extends TitleVM {
    public ObservableField<PostHouseHzBean> postBean = new ObservableField<>(new PostHouseHzBean());

    public ObservableField<String> cityT = new ObservableField<>("");
    public ObservableField<String> imgs = new ObservableField<>();
    public ObservableField<String> quarters = new ObservableField<>();
    public ObservableField<String> address = new ObservableField<>();
    public ObservableField<String> roomname = new ObservableField<>();
    public ObservableField<String> HouseType = new ObservableField<>("");
    public ObservableField<String> totalArea = new ObservableField<>();

    public AddHouseHzVm(@NonNull Application application, BaseModel model) {
        super(application, model);
        setTitleText("添加合租房源");
    }

    public BindingCommand moreClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            Intent intent = new Intent(mActivity, AddMoreHzActivity.class);
            intent.putExtra(AppConfig.BUNDLE_KEY2,postBean.get());
            mActivity.startActivityForResult(intent,10086);
        }
    });


    public BindingCommand houseClick = new BindingCommand(() -> {
        Intent intent = new Intent(mActivity, ImproveHouseActivity.class);
        intent.putExtra(AppConfig.BUNDLE_KEY2,postBean.get());
        mActivity.startActivityForResult(intent,10086);
    });

    private ArrayList<LocalMedia> imgList = new ArrayList<>();
    public BindingCommand selHouseImg = new BindingCommand(() -> {
        RxPermissionsUtils.file(mActivity, (RxPermissionsUtils.Accept) () -> {
            PictureSelector.create(mActivity)
                    .openGallery(SelectMimeType.ofImage())
                    .isDisplayCamera(false)
                    .setImageEngine(GlideEngine.createGlideEngine())
                    .setMaxSelectNum(4)
                    .setMinSelectNum(1)
                    .setImageSpanCount(4)
                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                        @Override
                        public void onResult(ArrayList<LocalMedia> result) {
                            imgList.clear();
                            imgList.addAll(result);
                            setBannerImg(result);
                        }

                        @Override
                        public void onCancel() {

                        }
                    });
        });
    });

    Banner mBanner;
    public void setBanner(Banner banner) {
        mBanner = banner;
    }

    private void setBannerImg(ArrayList<LocalMedia> banner_data) {
        uploadList.clear();
        getQNYToken();

        mBanner.setAdapter(new BannerImageAdapter<LocalMedia>(banner_data) {
            @Override
            public void onBindView(BannerImageHolder holder, LocalMedia data, int position, int size) {
                GlideEngine.createGlideEngine().loadImage(mActivity,data.getPath(),holder.imageView);
            }
        });

        // 开启循环轮播
        mBanner.isAutoLoop(true);
        mBanner.setIndicator(new CircleIndicator(mActivity));
        mBanner.setScrollBarFadeDuration(1000);
        // 设置指示器颜色(TODO 即选中时那个小点的颜色)
        mBanner.setIndicatorSelectedColor(Color.GREEN);
        // 开始轮播
        mBanner.start();

    }

    /**
     * 获取七牛云token
     */
    private void getQNYToken() {
        model.getToken()
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {})
                .subscribe(new DisposableObserver<QiNiuYunBean>() {
                    @Override
                    public void onNext(QiNiuYunBean qiniuYunBean) {
                        if (ValidateUtils.isNotEmptyObjectOrString(qiniuYunBean) &&
                                ValidateUtils.isNotEmptyString(qiniuYunBean.getToken())) {
                            uploadQNY(qiniuYunBean.getToken());
                        } else {
                            ToastUtils.showShort( "请求失败，请联系管理员");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    public List<String> uploadList = new ArrayList<>();
    private void uploadQNY(String token) {
        for (LocalMedia l : imgList) {
            String suffix = l.getRealPath().substring(l.getRealPath().lastIndexOf("."));
            String key = "works/zgb/" + System.currentTimeMillis() + suffix;
            QiNiuYunUpload.uploadFileToQny(mActivity, l.getRealPath(), token, key, new QiNiuYunUploadCallBack() {
                @Override
                public void onSuccess(String url) {
                    uploadList.add(url);
                    LogUtils.e(uploadList.toString());

                }

                @Override
                public void onFail() {

                }

                @Override
                public void onProgress(String key, double progress) {

                }
            });


        }
    }

    public BindingCommand selCity = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            View rootView = View.inflate(mActivity, R.layout.dialog_address_my, null);
            MyAddressPickerView addressView = rootView.findViewById(R.id.apvAddress);

            MyCustomPopupWindow mPopupWindow = MyCustomPopupWindow.builder()
                    .contentView(rootView)
                    .customListener((contentView) -> {
                    })
                    .activity(mActivity)
                    .isWrapHeight(true)
                    .gravity(Gravity.BOTTOM)
                    .build();
            mPopupWindow.show(0.5f);
            addressView.setOnAddressPickerSure((address, province, provinceCode, city, cityCode, area, areaCode) -> {
                if (city.equals("市辖区") || city.equals("县")) {
                    cityT.set(province);
                } else {
                    cityT.set(city);
                }
                mPopupWindow.dismiss();
            });

            addressView.setOnAddressPickerCancelListener(() -> {
                cityT.set("请选择");
                mPopupWindow.dismiss();
            });

        }
    });
    public BindingCommand selQuarters = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            getQuartersData();
        }
    });

    private void getQuartersData() {
        Map<String,String> map = new HashMap<>();
        map.put("userid",model.getLoginInfo().getData().getUser_id());
        model.get_quarters(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {})
                .subscribe(new DisposableObserver<QuarterEntity>() {
                    @Override
                    public void onNext(QuarterEntity bean) {
                        if (bean.issucc){
                            showPop(bean.getData());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void showPop(List<QuarterEntity.DataDTO> data) {
        PopQuarters popQuarters = new PopQuarters(mActivity, data,new PopSelClick() {
            @Override
            public void sel(PopBean x) {
                if (x.getName().contains("&&")){
                    addQuarters(x.getName());
                }else {
                    quarters.set(x.getName());
                    address.set(x.getAddress());

                }
            }
        });
        PopUtils.showPop(mActivity,popQuarters,false);

    }

    /**
     * 添加小区
     */
    private void addQuarters(String add) {
        String[] s = add.split("&&");
        quarters.set(s[0]);
        cityT.set(s[1]);

        Map<String,String> map = new HashMap<>();
        map.put("userid",model.getLoginInfo().getData().getUser_id());

        map.put("village",s[0]);
        map.put("city",s[1]);
        map.put("address",s[2]);



        model.add_quarters(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {
                    DialogUtils.showLoading(mActivity,"数据处理中");
                })
                .subscribe(new DisposableObserver<BaseResult>() {
                    @Override
                    public void onNext(BaseResult bean) {
                        DialogUtils.stopLoading();
                        if (bean.issucc){
                            ToastUtils.showShort(bean.msg);
                            address.set(s[1]+s[2]);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        DialogUtils.stopLoading();
                    }

                    @Override
                    public void onComplete() {
                        DialogUtils.stopLoading();
                    }
                });

    }

    public BindingCommand postData = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (imgList.size() > 0){
                if (imgList.size() == uploadList.size()){
                    StringBuilder stringBuilder = new StringBuilder();
                    for (String localMedia : uploadList) {
                        stringBuilder.append(localMedia).append(",");
                    }
                    if (stringBuilder.toString().contains(",")){
                        imgs.set(stringBuilder.deleteCharAt(stringBuilder.length()-1).toString());
                    }else {
                        imgs.set(stringBuilder.toString());
                    }
                    postBean.get().setImgsrc(imgs.get());
                    postHouseData();
                }
            }else {
                postHouseData();
            }



        }
    });

    private void postHouseData() {
        if (ValidateUtils.isEmptyString(cityT.get())){
            ToastUtils.showShort("请选择小区所在城市");
            return;
        }

        postBean.get().setCity(cityT.get());
        if (ValidateUtils.isEmptyString(quarters.get())){
            ToastUtils.showShort("请选择小区名称");
            return;
        }
        postBean.get().setQuarters(quarters.get());
        postBean.get().setAddress(address.get());

        if (ValidateUtils.isEmptyString(roomname.get())){
            ToastUtils.showShort("请输入房源名");
            return;
        }
        postBean.get().setRoomname(roomname.get());

        if (ValidateUtils.isEmptyString(totalArea.get())){
            ToastUtils.showShort("请输入房屋面积");
            return;
        }
        postBean.get().setTotalArea(totalArea.get());

        if (ValidateUtils.isEmptyString(postBean.get().getRoomjson())){
            ToastUtils.showShort("请前往房间信息填写相关信息");
            return;
        }

        String postjson = GsonUtils.getStringFromBean(postBean.get());
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, String> map1 = objectMapper.readValue(postjson, Map.class);
            map1.put("userid",model.getLoginInfo().getData().getUser_id());
            model.addcotenancy(map1)
                    .compose(RxUtils.schedulersTransformer())
                    .compose(RxUtils.exceptionTransformer())
                    .doOnSubscribe(this)
                    .doOnSubscribe(disposable -> {
                        DialogUtils.showLoading(mActivity);
                    })
                    .subscribe(new DisposableObserver<BaseResult>() {
                        @Override
                        public void onNext(BaseResult bean) {
                            DialogUtils.stopLoading();
                            if (bean.issucc){
                                finish();
                            }

                        }

                        @Override
                        public void onError(Throwable e) {
                            DialogUtils.stopLoading();
                        }

                        @Override
                        public void onComplete() {
                            DialogUtils.stopLoading();
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
            DialogUtils.stopLoading();
        }



    }


}
